package com.srwl.mytx.widget;

import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bm.library.Info;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.adapter.MyMessageAdapter;
import com.srwl.mytx.adapter.WrapContentLinearLayoutManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.greendao.MessageDao;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.chatRow.BaseChatRow;
import com.srwl.mytx.widget.chatRow.ChatRowAudioPlayer;
import com.srwl.mytx.widget.chatRow.ChatRowImage;
import com.srwl.mytx.widget.chatRow.ChatRowVideo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.SyncScrollingRefreshLayout;

public class ChatMessageListView extends RelativeLayout implements BaseChatRow.ChatRowCallBack, Conversation.MessageListener {

    protected static final String TAG = "ChatMessageListView";
    protected RecyclerView rl_message;
    protected SyncScrollingRefreshLayout refreshLayout;
    protected Context context;
    private KeyboardAwareRelativeLayout rootLayout;
    protected MyMessageAdapter messageAdapter;
    private Conversation conversation;
    private List<Message> messageList = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private final int SIZE = 20;
    private Message targetMessage;
    //查询本地消息记录的开始索引，没有高亮目标消息的时候，就是默认值0，从最新的消息开始加载
    private int startIndex;
    private int targetIndex;
    private String highlightKeyWord;
    private int tryScrollCount;
    private boolean isFirst = true;
    //正在加载数据中
    private boolean loading;
    //消息列表正在由代码控制 滑动中
    private boolean scrolling;
    private boolean haveMorePullDownData = true;
    private boolean haveMorePullUpData = true;
    private boolean recyclerViewTouch;
    private InteractionListener listener;
    private boolean startScroll;//消息列表开始滚动标识
    private boolean scrollBottom;//滑动到底部标识

    public ChatMessageListView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs);
    }

    public ChatMessageListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ChatMessageListView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.my_chat_message_list, this);
        refreshLayout = findViewById(R.id.refresh_layout);
        rl_message = findViewById(R.id.rl_message);
    }

    public void initData(User targetUser, Conversation conversation, KeyboardAwareRelativeLayout rootLayout, Message targetMessage) {
        this.targetMessage = targetMessage;
        initData(targetUser, conversation, rootLayout);

    }

    public void initData(User chatTarget, Conversation conversation, KeyboardAwareRelativeLayout rootLayout) {
        this.conversation = conversation;
        conversation.setMessageListener(this);
        this.rootLayout = rootLayout;
        //这儿用addAll 而没有用 = ，是因为在Conversation 中并没有持有整个消息列表
        if (targetMessage == null) {
            List<Message> messages = conversation.firstLoadMessage(SIZE, startIndex);
            Collections.reverse(messages);
            messageList.addAll(messages);
        } else {
            highlightKeyWord = targetMessage.getHighlightKeyWord();
            MessageDao messageDao = DBManager.getInstance().getDaoSession().getMessageDao();
            targetIndex = (int) (messageDao.queryBuilder().where(MessageDao.Properties.CId.eq(targetMessage.getcId()), MessageDao.Properties.Created.ge(targetMessage.getCreated())).orderDesc(MessageDao.Properties.Created).count() - 1);
            long totalIndex = messageDao.queryBuilder().where(MessageDao.Properties.CId.eq(targetMessage.getcId())).orderDesc(MessageDao.Properties.Created).count() - 1;
            //以 targetIndex为中心点，计算分页的起始 索引

            if (targetIndex - SIZE / 2 < 0) {
                startIndex = 0;
                haveMorePullUpData = false;
            } else {
                startIndex = (int) (targetIndex - SIZE / 2);
            }

            Log.d(TAG, "initData: targetIndex: " + targetIndex + "  totalIndex:" + totalIndex + "  startIndex:" + startIndex);
            List<Message> messages = conversation.firstLoadMessage(SIZE, startIndex);
            Collections.reverse(messages);
            for (Message message : messages) {
                message.setHighlightKeyWord(highlightKeyWord);
            }
            messageList.addAll(messages);
        }
        Log.d(TAG, "initData: 第一次加载消息数量 ：" + messageList.size());
        messageAdapter = new MyMessageAdapter(context, chatTarget, messageList);
        layoutManager = new WrapContentLinearLayoutManager(context, RecyclerView.VERTICAL, false);
        rl_message.setLayoutManager(layoutManager);
        rl_message.setAdapter(messageAdapter);
        rl_message.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    startScroll = true;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    Log.d(TAG, "onScrolled: 滑动到底部了");
                    scrollBottom = true;
                } else {
                    scrollBottom = false;
                }
            }
        });

        // Log.d(TAG, "initData: 第一次加载消息的数量 " + messageList.size());

        initChatRowCallBack();

        //scrollToFirstUnreadItem();
        if (targetMessage == null) {//滑动到最后一条消息
            if (messageList != null && messageList.size() > 0) {
                int lastPosition = messageList.size() - 1;
                rl_message.smoothScrollToPosition(lastPosition);
                //  scrollToPosition(lastPosition);
            }
        } else {//滑动到目标高亮消息
            //因为消息显示是 做了一次反向，所以 position 是用 消息总长， 减去targetIndex 和startIndex的差，得出目标项在当前消息列中的位置索引，
            int position = (messageList.size() - 1) - (targetIndex - startIndex);
            if (position <= messageList.size() - 1) {
                //rl_message.scrollToPosition(position);
                //rl_message.smoothScrollToPosition(position);
                Log.d(TAG, "run: 滚动到高亮目标项:" + position);
                //  tryScrollCount = 0;
                // scrollToPosition(position);
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.d(TAG, "run: rl_message.getHeight()/2  :   " + rl_message.getHeight() / 2);
                        layoutManager.scrollToPositionWithOffset(position, rl_message.getHeight() / 2 - Utils.dpToPx(50, context));//rl_message.getHeight() / 2
                    }
                }, 50);//做一个延迟之后再滑动，是等待RecyclerView 加载数据
            }

        }

        rootLayout.addOnKeyboardShownListener(new KeyboardAwareRelativeLayout.OnKeyboardShownListener() {
            @Override
            public void onKeyboardShown() {
                Log.e(TAG, "onKeyboardShown: 键盘弹出，，，，，，，，，，，，，，，，，，，，，，，");
                if (messageList != null && messageList.size() > 0) {
                    int lastPosition = messageList.size() - 1;
                    tryScrollCount = 0;
                    //  scrollToPosition(lastPosition);
                }

            }
        });
        postDelayed(new Runnable() {
            @Override
            public void run() {

                initRefreshLayout();
            }
        }, 1000);
    }

//    private void initRefreshLayout(Conversation conversation) {
//        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
//                R.color.holo_orange_light, R.color.holo_red_light);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//
//            @Override
//            public void onRefresh() {
//                conversation.pullDownLoadMoreMessage();
//                swipeRefreshLayout.setRefreshing(false);
//            }
//        });
//    }


    void initRefreshLayout() {
        //refreshLayout.setDisableRefresh(true);


        if (targetMessage != null && haveMorePullUpData) {//开启上拉加载
            refreshLayout.setDisableLoadMore(false);
            refreshLayout.setEnableAutoLoadMore(true);
        } else {
            refreshLayout.setDisableLoadMore(true);
            refreshLayout.setEnableAutoLoadMore(false);
        }
        if (haveMorePullDownData) {
            refreshLayout.setEnableAutoRefresh(true);
        } else {
            refreshLayout.setDisableRefresh(true);
        }
        refreshLayout.setEnableSmoothRollbackWhenCompleted(true);
        refreshLayout.setDisableLoadMoreWhenContentNotFull(true);
        refreshLayout.setEnableNextPtrAtOnce(false);
        // refreshLayout.autoRefresh(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                Log.d(TAG, "onRefreshing: 触发下拉加载");
                if (!recyclerViewTouch) {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onScrolled: 非触摸滑动消息列表，不做消息加载");
                    return;
                }
                recyclerViewTouch = false;
                if (haveMorePullDownData) {
                    conversation.pullDownLoadMoreMessage();
                }
            }

            @Override
            public void onLoadingMore() {
                Log.d(TAG, "onLoadingMore: 触发上拉加载");
                if (!recyclerViewTouch) {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onScrolled: 非触摸滑动消息列表，不做消息加载");
                    return;
                }
                recyclerViewTouch = false;
                if (haveMorePullUpData) {
                    conversation.pullUpLoadMoreMessage();
                }
            }
        });

        rl_message.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                //Log.d(TAG, "onTouch: 触摸消息列表了，，");
                recyclerViewTouch = true;
                if (listener != null) {
                    listener.onTouch();
                }
                return false;
            }
        });


//        rl_message.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
//                if(newState==RecyclerView.SCROLL_STATE_IDLE||newState==RecyclerView.SCROLL_STATE_DRAGGING){
//                    //show 手指拖拽和停止均可展示图片
//                   messageAdapter .setScrolling(false);
//                    //通知adapter恢复getview中的图下载
//                    if(Glide.with(context).isPaused())Glide.with(context).resumeRequests();
//                }else {
//                    //hide
//                    messageAdapter.setScrolling(true);
//                }
//            }
//        });

//        setOnTouchListener(new OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                Log.d(TAG, "onTouch: 触摸消息列表了，，");
//                recyclerViewTouch = true;
//                return false;
//            }
//        });
//
//        rl_message.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//
//                int firstCompletelyVisibleItemPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
//                if (firstCompletelyVisibleItemPosition == 0) {
//                    Log.d(TAG, "onScrolled: 滑动到了顶部");
//                    if (!recyclerViewTouch) {
//                        Log.d(TAG, "onScrolled: 非触摸滑动消息列表，不做消息加载");
//                        return;
//                    }
//                    recyclerViewTouch = false;
//                    if (!haveMorePullDownData) {
//                        Log.d(TAG, "onScrolled: 下拉没有更多消息了可加载了");
//                        return;
//                    }
//                    if (checkLoading()) return;
//                    ChatMessageListView.this.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            messageAdapter.showHeader();
//                            rl_message.smoothScrollToPosition(0);
//                        }
//                    }, 20);
//                    // refreshLayout.autoRefresh(true, true);
//                    conversation.pullDownLoadMoreMessage();
//                }
//
//                if (targetMessage != null) {
//                    int lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition();
//                    if (lastCompletelyVisibleItemPosition == layoutManager.getItemCount() - 1) {
//                        Log.d(TAG, "onScrolled: 滑动到了底部");
//                        if (!recyclerViewTouch) {
//                            Log.d(TAG, "onScrolled: 非触摸滑动消息列表，不做消息加载");
//                            return;
//                        }
//                        recyclerViewTouch = false;
//                        if (!haveMorePullUpData) {
//                            return;
//                        }
//                        if (checkLoading()) return;
//                        rl_message.postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                messageAdapter.showFooter();
//                                //移动到最后一个，让footer 显示出来，此刻适配器里面的 getItemCount（）方法里面，强制加了1，所以这儿 显示最后一条，直接以数据集的长度即可
//                                rl_message.smoothScrollToPosition(messageList.size());
//                            }
//                        }, 20);
//                        conversation.pullUpLoadMoreMessage();
//                    }
//                }
//            }
//        });
    }

    synchronized private boolean checkLoading() {
        if (loading) {
            Log.d(TAG, "onScrolled: 当前正在下拉加载数据中，当前请求属于重复请求，过滤掉");
            return true;
        }
        loading = true;
        return false;
    }

    public void refresh() {
        messageAdapter.notifyDataSetChanged();
    }

    public void refresh(User targetUser) {
        if (targetUser == null) {
            return;
        }
        messageAdapter.refresh(targetUser);
    }

    /**
     * 定位第一条接收到的未读消息
     */
    public void scrollToFirstUnreadItem() {
        int position = messageList.size() - 1;
        for (int i = 0; i < messageList.size(); i++) {
            if (!Utils.isSendMessage(messageList.get(i)) && messageList.get(i).getReadState() == Constant.MESSAGE_READ_STATE_UNREAD) {
                position = i;
                break;
            }
        }
        if (position >= 0) {
            rl_message.smoothScrollToPosition(position);
        }
    }


    /**
     * 移动 item 到 完全 可见的位置
     *
     * @param position
     */
    public void scrollItemVisible(int position) {
        //重置 recyclerViewTouch 为false,是为了避免用代码控制消息列表滑动的时候，消息列表滑动到顶部或者底部，触发消息加载事件
        recyclerViewTouch = false;
        scrolling = false;
        tryScrollCount = 0;
        Log.d(TAG, "scrollItemVisible:判断目标项是否可见 position ：" + position);
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //判断 目标item  是否在可见范围，如果不是，则移动 列表，让目标项 显示出来
        if (position < firstVisibleItemPosition || position > lastVisibleItemPosition) {
            Log.d(TAG, "scrollItemVisible:目标项不可见，移动目标项到可见位置 position ：" + position);
            //移动item到可见位置
            rl_message.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    checkItemVisibleGlobal(position);
                    rl_message.removeOnScrollListener(this);
                }
            });
            layoutManager.scrollToPosition(position);
            layoutManager.setStackFromEnd(true);
        } else {
            Log.d(TAG, "scrollItemVisible: 目标项可见，判断是否完全可见");
            checkItemVisibleGlobal(position);
        }

    }


    public void scrollToPosition(int position) {
        Log.d(TAG, "scrollToPosition: 滑动到目标位置 position:" + position);
        //重置 recyclerViewTouch 为false,是为了避免用代码控制消息列表滑动的时候，消息列表滑动到顶部或者底部，触发消息加载事件
        recyclerViewTouch = false;
        scrolling = true;
        rl_message.smoothScrollToPosition(position);
        rl_message.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                rl_message.removeOnScrollListener(this);
                checkItemVisibleGlobal(position);
            }
        });
    }

    /**
     * 判断 item 是否全部可见
     *
     * @param position
     */
    private void checkItemVisibleGlobal(int position) {
        Log.d(TAG, "checkItemVisibleGlobal: 判断目标项是否完全可见 position：" + position);
        // View itemView = layoutManager.findViewByPosition(position);
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        View itemView = rl_message.getChildAt(position - firstVisibleItemPosition);
        if (itemView == null) {//todo 有时候目标项打印出来是空的，但是 在消息列表中，却是显示出来了的，难道是 view 还没绘制完成?可是 本方法都是在 recyclerView 滑动停止后 才调用的。
            if (tryScrollCount <= 1) {
                Log.e(TAG, "checkItemVisibleGlobal: 目标项为空 position ：" + position + "   尝试再次滑动，尝试滑动次数：" + tryScrollCount);
                tryScrollCount++;
                scrollToPosition(position);
            } else {
                scrolling = false;
                Log.e(TAG, "checkItemVisibleGlobal: 目标项为空 position ：" + position + "   尝试滑动从技术超过限制，不再尝试滑动");
            }
            return;
        }
        if (!itemView.isShown()) {
            if (tryScrollCount <= 1) {
                Log.w(TAG, "checkItemVisibleGlobal:  目标项不可见 position ：" + position + "  尝试再次滑动，尝试滑动次数：" + tryScrollCount);
                tryScrollCount++;
                scrollToPosition(position);
            } else {
                scrolling = false;
                Log.w(TAG, "checkItemVisibleGlobal:  目标项不可见 position：" + position + "   尝试滑动从技术超过限制，不再尝试滑动");
            }
            return;
        }
        RecyclerView.ViewHolder childView = rl_message.getChildViewHolder(itemView);
        BaseChatRow baseChatRow = (BaseChatRow) childView;
        Log.d(TAG, "checkItemVisibleGlobal: " + baseChatRow.getMessage().toString());

        try {
            setFixHideForRecyclerView(rl_message, childView.itemView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /***
     * 解决列表图片被遮挡时 RecyclerView 滑动一段距离 显示出完整的预览图
     * 根据getLocalVisibleRect 相对view自身坐标计算偏移量 只要top和left都是0 right等于view宽度 bottom等于view高度 即图片没有被隐藏
     * 上面被隐藏 top肯定大于0 滑动偏移量即为-top
     * 下面被隐藏 bottom肯定小于 view高度 偏移量即为view高度-bottom
     *
     */
    public void setFixHideForRecyclerView(RecyclerView recyclerView, View view) {
        if (null != recyclerView && null != view) {
            int height = view.getHeight();
            Rect rect = new Rect();
            view.getLocalVisibleRect(rect);
            if (rect.top > 0 && rect.left == 0 && rect.bottom == height) {
                //上面被遮挡
                Log.d(TAG, "setFixHideForRecyclerView: 上面被遮挡");
                int offset = rect.top;
                recyclerView.scrollBy(0, -offset);
            } else if (rect.top == 0 && rect.left == 0 && rect.bottom < height) {
                //下面被遮挡
                Log.d(TAG, "setFixHideForRecyclerView: 下面被遮挡");
                int offset = height - rect.bottom;
                recyclerView.scrollBy(0, offset);
            } else {
                Log.d(TAG, "setFixHideForRecyclerView: 没有被遮挡");
            }
        }
        scrolling = false;
    }


    /**
     * 选中position对应的item，并获取图片Info
     *
     * @param position
     * @return
     */
    public Info getImageInfo(int position) {
        Log.d(TAG, "getImageInfo: 获取名表项在屏幕中的位置信息 position:" + position);
        int firstVisiblePosition;
        // rl_message.smoothScrollToPosition(position);
        //我们断定 position 对应的 item 一定是可见的
        View itemView = layoutManager.findViewByPosition(position);
        // firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
        //View itemView = rl_message.getChildAt(position - firstVisiblePosition);
        if (itemView == null) {
            Log.e(TAG, "getImageInfo: 目标项为空 position ：" + position);

            return null;
        }

        if (!itemView.isShown()) {
            Log.e(TAG, "getImageInfo: 目标项不可见 position ：" + position);
            return null;
        }
        RecyclerView.ViewHolder childView = rl_message.getChildViewHolder(itemView);
        if (childView instanceof ChatRowImage) {
            ChatRowImage chatRowImage = (ChatRowImage) childView;
            try {
                setFixHideForRecyclerView(rl_message, childView.itemView);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return chatRowImage.getImageRectInfo();
        } else if (childView instanceof ChatRowVideo) {
            ChatRowVideo chatRowVideo = (ChatRowVideo) childView;
            try {
                setFixHideForRecyclerView(rl_message, childView.itemView);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return chatRowVideo.getImageRectInfo();
        }
        return null;

    }


    public void setItemClickListener(MyMessageAdapter.MessageListItemClickListener itemClickListener) {
        //  this.itemClickListener = itemClickListener;
        messageAdapter.setItemClickListener(new MyMessageAdapter.MessageListItemClickListener() {
            @Override
            public void onResendClick(Message message) {
                itemClickListener.onResendClick(message);
            }

            @Override
            public boolean onBubbleClick(Message message) {
                startScroll = false;//当消息点击的时候，重置消息列表开始滚动的状态
                return itemClickListener.onBubbleClick(message);
            }

            @Override
            public void onBubbleLongClick(Message message) {
                itemClickListener.onBubbleLongClick(message);
            }

            @Override
            public void onUserAvatarClick(String userId) {
                itemClickListener.onUserAvatarClick(userId);
            }

            @Override
            public void onUserAvatarLongClick(String username) {
                itemClickListener.onUserAvatarLongClick(username);
            }

            @Override
            public void onImageOrVideoRowClick(int position, Info imageInfo) {
                itemClickListener.onImageOrVideoRowClick(position, imageInfo);
            }
        });
    }

    private void initChatRowCallBack() {

//         chatRowCallBack = new BaseChatRow.ChatRowCallBack() {
//            @Override
//            public void onMessageUpdate(YWMessage message, int position) {
//                conversation.getMessageLoader().updateMessageTODB(message);
//                messageAdapter.notifyItemChanged(position);
//            }
//
//            @Override
//            public void onMessageRead(YWMessage message) {
//                message.setMsgReadStatus(YWMessage.MSG_READED_STATUS);
//                conversation.getMessageLoader().updateMessageTODB(message);
//                conversation.setMsgReadedStatusToServer(message, null);
//            }
//
//            @Override
//            public void onAudioPlayCompletion(int position) {
//
//                for (int i = position + 1; i < messageListView.size(); ++i) {
//                    YWMessage msg = messageListView.get(i);
//                    String authorId = msg.getAuthorUserId();
//                    int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
//                    int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
//                    if (msg.getSubType() == YWMessage.SUB_MSG_TYPE.IM_AUDIO
//                            && authorId != null
//                            && !EaseCommonUtils.isSendMessage(msg)
//                            && ((YWAudioMessageBody) msg.getMessageBody()).getHasRead() != YWMessageType.ReadState.read
//                            && ((YWFileMessageBody) msg.getMessageBody()).getDownloadState() == YWMessageType.DownloadState.success) {
//
//                        //移动消息列表，让自动播放的项处于可见位置
//                        if (i > lastVisibleItemPosition - 1) {
//                            Log.d(TAG, "移动消息列表前，第一个可见项位置：" + firstVisibleItemPosition);
//                            //
//                            Log.d(TAG, "自动播放，移动到目标项：" + i);
//                            // rl_message.smoothScrollToPosition(i);
//                            // rl_message.scrollToPosition(position);
//                            layoutManager.scrollToPositionWithOffset(position, 0);
//                            layoutManager.setStackFromEnd(true);
//                            //滑动之后，必须重新获取第一个可见项的position
//                            firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
//                            Log.d(TAG, "移动消息列表后，第一个可见项位置：" + firstVisibleItemPosition);
//                        }
//
//                        //获取目标语音消息行
//                        View itemView = rl_message.getChildAt(i - firstVisibleItemPosition);
//                        if (itemView != null) {
//                            ChatRowVoice item = (ChatRowVoice) rl_message.getChildViewHolder(itemView);
//                            if (item != null) {
//                                item.autoPlay();
//                            }
//                        } else {
//                            Log.e(TAG, "获取到的item空，数据集索引为：" + i);
//                        }
//
//                        break;
//
//
//                    }
//                }
//
//            }
//
//        };
        messageAdapter.setChatRowCallBack(this);
    }

    public List<Message> getMessageList() {
        return messageList;
    }

    @Override
    public void onMessageRead(Message message) {

        conversation.setMessageRead(message);

    }

    @Override
    public void onAudioPlayCompletion(int position) {

        for (int i = position + 1; i < messageList.size(); ++i) {
            Message msg = messageList.get(i);
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
            int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
            if (msg.getSubType() == Constant.IM_TYPE_AUDIO
                    && !isSendMessage(msg)
                    && msg.getReadState() != Constant.MESSAGE_READ_STATE_READ
                    && msg.getDownloadState() == Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS) {
                conversation.setMessageRead(msg);
                ChatRowAudioPlayer.getInstance(context).play(msg, new ChatRowAudioPlayer.AudioPlayerInteractionListener() {
                    @Override
                    public void onStartPlay() {

                    }

                    @Override
                    public void onBreakPlay() {

                    }

                    @Override
                    public void onCompletePlay() {
                        onAudioPlayCompletion(position + 1);
                    }

                    @Override
                    public void onError(int errorCode, String message) {

                    }
                });


                //移动消息列表，让自动播放的项处于可见位置
                if (i > lastVisibleItemPosition) {
                    Log.d(TAG, "移动消息列表前，第一个可见项位置：" + firstVisibleItemPosition);
                    //
                    // Log.d(TAG, "自动播放，移动到目标项：" + i);
                    // rl_message.smoothScrollToPosition(i);
                    // rl_message.scrollToPosition(position);
                    //如果消息列表被拖动了，就不移动 语音消息item
                    messageAdapter.notifyItemChanged(i);
                    if (!startScroll) {
                        layoutManager.scrollToPosition(i);
                        layoutManager.setStackFromEnd(true);
                    }
                    //滑动之后，必须重新获取第一个可见项的position
                    //  int finalI = i;
//                    rl_message.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
//                            Log.d(TAG, "移动消息列表后，第一个可见项位置：" + firstVisibleItemPosition);
//                            //获取目标语音消息行
//                            View itemView = rl_message.getChildAt(finalI - firstVisibleItemPosition);
//                            if (itemView != null) {
//                                ChatRowVoice item = (ChatRowVoice) rl_message.getChildViewHolder(itemView);
//                                if (item != null) {
//                                    item.autoPlay();
//                                }
//                            } else {
//                                Log.e(TAG, "获取到的item空，数据集索引为：" + finalI);
//                            }
//                        }
//                    }, 100);
                } else {
                    //通知语音消息行刷新
                    messageAdapter.notifyItemChanged(i);
                    //获取目标语音消息行
//                    View itemView = rl_message.getChildAt(i - firstVisibleItemPosition);
//                    if (itemView != null) {
//                        ChatRowVoice item = (ChatRowVoice) rl_message.getChildViewHolder(itemView);
//                        if (item != null) {
//                            item.autoPlay();
//                        }
//                    } else {
//                        Log.e(TAG, "获取到的item空，数据集索引为：" + i);
//                    }
                }
                break;
            }
        }
        //判断当前自动播放是否完成，完成后，把消息列表滚动状态重置为 false,消息列表拖动状态起作用的截止点为 当次自动播放结束，下次自动播放的时候，又会自动显示出屏幕外的 语音消息item
        if (position + 1 >= messageList.size()) {
            startScroll = false;
        }
    }

    @Override
    public void onFileMessageDownLoadComplete(int position) {
        if (loading || scrolling) {//如果正在加载消息中，就不判断目标item是否完全显示
            Log.d(TAG, "onFileMessageDownLoadComplete: 加载数据中或者移动消息列表中，，不判断文件类型消息，是否完全显示");
            return;
        }
        //如果是消息列表的最后一项，判断是否完全可见
//        if (position == messageList.size() - 1) {
//            postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    checkItemVisibleGlobal(position);
//                }
//            }, 150);
//        }
    }

    public static boolean isSendMessage(Message message) {
        return message.getFromId().equals(UserProfileManager.getInstance().getLoginUserInfo().getuId());
    }

    @Override
    public void onPullDownLoadMoreLocalMessage(List<Message> messages) {
        //对消息列表进行反转，因为从数据库读取是按创建时间降序排列的，
        Collections.reverse(messages);
        final int size = messages.size();
        Log.d(TAG, "onPullDownLoadMoreLocalMessage: 下拉加载更多消息 消息数量：" + size);

        if (size < SIZE) {
            haveMorePullDownData = false;
            refreshLayout.setDisableRefresh(true);
            refreshLayout.setEnableAutoRefresh(false);
        }
        if (size == 0) {
            ChatMessageListView.this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //  messageAdapter.hideHeader();
                    refreshLayout.refreshComplete();
                    loading = false;
                }
            }, 500);
            return;
        }
        if (!TextUtils.isEmpty(highlightKeyWord)) {
            for (Message message : messages) {
                message.setHighlightKeyWord(highlightKeyWord);
            }
        }

        //下拉加载的本地消息，插入到消息列表最前面
        ChatMessageListView.this.postDelayed(new Runnable() {
            @Override
            public void run() {
                messageList.addAll(0, messages);
                //    messageAdapter.hideHeader();
                messageAdapter.notifyItemRangeInserted(0, size);
                loading = false;
                refreshLayout.refreshComplete();
                //可以不刷新 新插入消息后面的item,因为 所有操作都是操作的item 中的message,而不是 适配器中的 position ，
                //  messageAdapter.notifyItemRangeChanged(size + 1, messageList.size() - (size + 1));
                // rl_message.smoothScrollToPosition(messages.size() - 1);
            }
        }, 500);

    }

    @Override
    public void onPullUpLoadMoreLocalMessage(List<Message> messages) {
        //对消息列表进行反转，因为从数据库读取是按创建时间降序排列的，
        Collections.reverse(messages);
        final int size = messages.size();
        Log.d(TAG, "onPullUpLoadMoreLocalMessage: 上拉加载更多消息 消息数量：" + size);
        if (size < SIZE) {
            haveMorePullUpData = false;
            refreshLayout.setDisableLoadMore(true);
            refreshLayout.setEnableAutoLoadMore(false);
        }
        if (size == 0) {
            ChatMessageListView.this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // messageAdapter.hideFooter();
                    refreshLayout.refreshComplete();
                    loading = false;
                }
            }, 500);
            return;
        }
        if (!TextUtils.isEmpty(highlightKeyWord)) {
            for (Message message : messages) {
                message.setHighlightKeyWord(highlightKeyWord);
            }
        }
        //上拉加载的添加到消息集合后面
        int startInsertIndex = messageList.size() - conversation.getNewMessageSize();
        ChatMessageListView.this.postDelayed(new Runnable() {
            @Override
            public void run() {
                messageList.addAll(startInsertIndex, messages);
                //  messageAdapter.hideFooter();
                messageAdapter.notifyItemRangeInserted(startInsertIndex, size);
                loading = false;
                refreshLayout.refreshComplete();
                // rl_message.smoothScrollToPosition(startInsertIndex);
            }
        }, 500);
    }

    @Override
    public void onNoMorePullDownMessage() {
        haveMorePullDownData = false;
        refreshLayout.setDisableRefresh(true);
        refreshLayout.setEnableAutoRefresh(false);
    }


    @Override
    public void onReceiveMessage(Message message) {
        messageList.add(message);
        int lastPosition = messageList.size() - 1;
        messageAdapter.notifyItemInserted(lastPosition);
        if (scrollBottom || Utils.isSendMessage(message)) {
            rl_message.smoothScrollToPosition(lastPosition);
        }
        //在这儿直接调用以下方法，实现图片类型消息滑动后完全可见，行不通，因为去判断是否完全可见的时候，图片可能没有下载完成，显示的是占位图，
        //所以需要等加载完成后，预览图显示出来后，再判断是否完全可见
        //scrollToPosition(lastPosition);
    }

    @Override
    public void onMessageDelete(Message deleteMessage) {

        //这样没有删除动画效果
//        messageList.removeAll(messages);
//        messageAdapter.notifyDataSetChanged();

        //这样有删除动画效果
        int index = messageList.indexOf(deleteMessage);
        messageList.remove(index);
        messageAdapter.notifyItemRemoved(index);
        messageAdapter.notifyItemRangeChanged(index, messageList.size() - index);

    }

    @Override
    public void onDeleteAllMessage() {
        messageList.clear();
        messageAdapter.notifyDataSetChanged();
    }

    /**
     * 发送状态更新，该消息在开始发送的时候，以发送中的状态 添加进了消息列表，
     * 直接拿到 索引，更新适配器即可，
     * 因为消息状态在 消息处理器中已经修改了
     *
     * @param updateMessage
     */
    @Override
    public void onMessageSendStateChange(Message updateMessage) {
        // 不能以下面的形式获取索引，因为他们可能已经不是同一个对象了
        //  int index = messageList.indexOf(updateMessage);
        for (int i = 0; i < messageList.size(); i++) {
            Message message = messageList.get(i);
            if (TextUtils.equals(message.getId(), updateMessage.getId())) {
                message.setSendState(updateMessage.getSendState());
                messageAdapter.notifyItemChanged(i);

            }
        }

    }

    /**
     * 这是一条消息已读回执，该消息对象并没有存在消息列表，
     * 所以没法通过对象拿到索引，消息回执的id 和原消息是一致的
     * 所以可以通过遍历消息列表，比对消息id，更新已读状态，再刷新界面
     *
     * @param updateMessage
     */
    @Override
    public void onMessageReadStateChange(Message updateMessage) {
        for (int i = 0; i < messageList.size(); i++) {
            Message message = messageList.get(i);
            //回值消息中的 content 是目标消息的ID
            if (message.getId().equals(updateMessage.getContent())) {
                message.setReadState(Constant.MESSAGE_READ_STATE_READ);
                messageAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    @Override
    public void onTargetUserInfoRefresh(User targetUser) {
        refresh(targetUser);
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        void onTouch();
    }

}
